---------------------------------------------------------------
-- @Description：         watchdog
---------------------------------------------------------------
require "skynet.manager"
local skynet = require "skynet"
local log = require "sky_log"
local cc = require "sky_call"

local agent = {}
local CMD = {}
local gate
local MESSAGE_CGATE_TYPE = 101

--============================= Local Function =============================--
local function close_agent(fd)
	-- log.info("agent =", agent)
	-- log.info("close_agent fd=", fd)
	local a = agent[fd]
	if a then
		skynet.send(a, "lua", "disconnect")
		skynet.call(".robot_manager", "lua", "on_disconnect_agent", a)
	end
	
	agent[fd] = nil
end

--============================= CGATE MSG =============================--
local CGATE = {}
function CGATE.warning(msg)
	local fd = tonumber(msg[2])
	log.warning("watchdog SOCKET.warning fd=", fd)
end

function CGATE.close(msg)
	local fd = tonumber(msg[2])
	log.info("watchdog SOCKET.close fd=", fd)

	close_agent(fd)
end

function CGATE.connected(msg)
	local _agent = tonumber(msg[2])
	local _fd = tonumber(msg[3])

	if _agent and _fd then 
		agent[_fd] = _agent
		skynet.send(_agent, "lua", "connected", { gate=gate, fd=_fd, watchdog=skynet.self()})

		--log.info("connected watchdog agent_t=", agent)
	end
end

function CGATE.dispatch_msg(session, source, message)
    --log.info("cgate msg: session=", session)
    --log.info("cgate msg: from=", source)
    --log.info("cgate msg: message=", message)

	local t = {}
	local str = string.gsub(message, "#", " ")
	for v in string.gmatch(str, "(%S+)") do   
		table.insert(t, v)
	end
	--log.info("get cgate_msg=", t)

	local f = CGATE[t[1]]
	if f then 
		f(t)
	end
end

skynet.register_protocol {
    name = "cgate_msg",
    id = MESSAGE_CGATE_TYPE,
    pack = function(msg)
        local str = ''
        if type(msg)~='table' then 
            str = tostring(msg)
        else
            for _, v in ipairs(msg) do 
                str=str..v.."#"
            end
        end
		--log.info("cgate pack str=", str)
        return str 
    end,
    unpack = skynet.tostring,
    dispatch = function(session, from, message, sz)
        CGATE.dispatch_msg(session, from, message)
    end
}

function CMD.debug_get_infos()
	log.warning("agent_t=", agent)
end

function CMD.debug_cgate_infos()
	cc.send_cgate({"debug_infos"})
end

skynet.start(function()
	skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
		local f = assert(CMD[cmd])
		skynet.ret(skynet.pack(f(subcmd, ...)))
	end)

	skynet.register(".csocket_watchdog")

	local ipoker = skynet.getenv("ipoker")
	if not ipoker or ipoker == 0 then
		gate = skynet.launch("service_csocket_gate")
	else
		gate = skynet.launch("service_ipksocket_gate")
	end

	skynet.timeout(100, function()
		cc.send_cgate( {"initialization", skynet.self()} )
	end)
end)
